/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  void flatten(TreeNode* root) {

    while(root != nullptr){
      if(root->left == nullptr){
        root = root->right;
      }else{
        // 找左子树最右边的节点
        TreeNode *pre = root->left;
        while(pre->right != nullptr){
          pre = pre->right;
        }
        // 将原来右子树的节点接到左子树最右边的节点
        pre->right = root->right;
        // 将左子树插入到右子树的位置
        root->right = root->left;
        root->left = nullptr;
        // 进入下一个节点
        root->right;
      }
    }

  }
};